#include <iostream>
#include <ctime>
#include <map>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include "BlockQueue.hpp"
#include "Task.hpp"

using std::cout;
using std::endl;


void* consumer(void* _bq)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(_bq);

    while (true)
    {
        Task t;
        bq->pop(&t);

        cout << "消费数据：" << t() << endl;

        //cout << "消费数据：" << data << endl;
        sleep(1);
    }

    return nullptr;
}

void* producer(void* _bq)
{
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(_bq);

    std::map<char, std::function<int(int, int)>> oper_func = 
    {
        {'+', [](int x, int y) { return x + y; }},
        {'-', [](int x, int y) { return x - y; }},
        {'*', [](int x, int y) { return x * y; }},
        {'/', [](int x, int y) { 
                if (y==0) 
                {
                    cout << "除0错误" << endl;
                    return -1;
                }
                return x / y;
            }
        },
        {'%', [](int x, int y) { 
                if (y==0) 
                {
                    cout << "模0错误" << endl;
                    return -1;
                }
                return x % y;
            }
        }
    };
    std::string oper = "+-*/";

    while (true)
    {
        int x = rand() % 10 + 1;
        int y = rand() % 5;
        char op = oper[rand() % oper.size()];
        Task tk(x, y, op, oper_func[op]);
        bq->push(tk);
        cout << "生产数据：" << tk.toStringTask() << endl;

        sleep(1);
    }

    return nullptr;
}

int main()
{
    srand((size_t)time(nullptr) ^ getpid());

    BlockQueue<Task> *bq = new BlockQueue<Task>();

    pthread_t c, p;

    pthread_create(&p, nullptr, producer, (void*)bq);
    pthread_create(&c, nullptr, consumer, (void*)bq);

    pthread_join(c, nullptr);
    pthread_join(p, nullptr);

    return 0;
}